import React, { useState, useCallback } from "react";
import { Responsive, WidthProvider } from "react-grid-layout";
import type { Layout } from "react-grid-layout";
import { Button, Drawer, List, Switch, App } from "antd";
import {
  SettingOutlined,
  AppstoreOutlined,
  ReloadOutlined,
} from "@ant-design/icons";

import AnnouncementWidget from "./AnnouncementWidget";
import TaskWidget from "./TaskWidget";
import HotNewsWidget from "./HotNewsWidget";
import ToolsWidget from "./ToolsWidget";
import BillAnalysisWidget from "./BillAnalysisWidget";
import PlaceholderWidget from "./PlaceholderWidget";

// 导入样式
import "react-grid-layout/css/styles.css";
import "react-resizable/css/styles.css";

const ResponsiveGridLayout = WidthProvider(Responsive);

// 可用的组件类型 - 天气模块不参与自定义
const WIDGET_TYPES = {
  announcement: { name: "公告", component: AnnouncementWidget },
  task: { name: "任务", component: TaskWidget },
  hotNews: { name: "今日热点", component: HotNewsWidget },
  tools: { name: "常用工具", component: ToolsWidget },
  billAnalysis: { name: "账单分析", component: BillAnalysisWidget },
  placeholder: { name: "占位模块", component: PlaceholderWidget },
};

// 自定义布局配置 - 按照指定位置排列
const DEFAULT_LAYOUTS = {
  lg: [
    // 账单分析 - 左上角
    { i: "billAnalysis", x: 0, y: 0, w: 3, h: 3, minW: 2, minH: 2 },
    // 公告 - 右上角
    { i: "announcement", x: 9, y: 0, w: 3, h: 3, minW: 2, minH: 2 },
    // 今日热点 - 左侧中间
    { i: "hotNews", x: 0, y: 3, w: 3, h: 4, minW: 2, minH: 3 },
    // 任务 - 中间上部
    { i: "task", x: 3, y: 0, w: 6, h: 4, minW: 3, minH: 3 },
    // 常用工具 - 任务下面
    { i: "tools", x: 3, y: 4, w: 6, h: 3, minW: 3, minH: 2 },
    // 占位模块 - 右侧剩余空间
    { i: "placeholder", x: 9, y: 3, w: 3, h: 4, minW: 2, minH: 3 },
  ],
  md: [
    // 账单分析 - 左上角
    { i: "billAnalysis", x: 0, y: 0, w: 2, h: 3, minW: 2, minH: 2 },
    // 公告 - 右上角
    { i: "announcement", x: 6, y: 0, w: 2, h: 3, minW: 2, minH: 2 },
    // 今日热点 - 左侧中间
    { i: "hotNews", x: 0, y: 3, w: 2, h: 4, minW: 2, minH: 3 },
    // 任务 - 中间上部
    { i: "task", x: 2, y: 0, w: 4, h: 4, minW: 3, minH: 3 },
    // 常用工具 - 任务下面
    { i: "tools", x: 2, y: 4, w: 4, h: 3, minW: 3, minH: 2 },
    // 占位模块 - 右侧剩余空间
    { i: "placeholder", x: 6, y: 3, w: 2, h: 4, minW: 2, minH: 3 },
  ],
  sm: [
    // 小屏幕垂直排列
    { i: "billAnalysis", x: 0, y: 0, w: 2, h: 2, minW: 2, minH: 2 },
    { i: "announcement", x: 2, y: 0, w: 2, h: 2, minW: 2, minH: 2 },
    { i: "task", x: 0, y: 2, w: 4, h: 3, minW: 2, minH: 2 },
    { i: "tools", x: 0, y: 5, w: 4, h: 2, minW: 2, minH: 2 },
    { i: "hotNews", x: 0, y: 7, w: 4, h: 4, minW: 2, minH: 3 },
    { i: "placeholder", x: 0, y: 11, w: 4, h: 2, minW: 2, minH: 2 },
  ],
  xs: [
    // 移动端垂直排列
    { i: "billAnalysis", x: 0, y: 0, w: 2, h: 2, minW: 2, minH: 2 },
    { i: "announcement", x: 0, y: 2, w: 2, h: 2, minW: 2, minH: 2 },
    { i: "task", x: 0, y: 4, w: 2, h: 3, minW: 2, minH: 2 },
    { i: "tools", x: 0, y: 7, w: 2, h: 2, minW: 2, minH: 2 },
    { i: "hotNews", x: 0, y: 9, w: 2, h: 4, minW: 2, minH: 3 },
    { i: "placeholder", x: 0, y: 13, w: 2, h: 2, minW: 2, minH: 2 },
  ],
  xxs: [
    // 超小屏幕垂直排列
    { i: "billAnalysis", x: 0, y: 0, w: 1, h: 2, minW: 1, minH: 2 },
    { i: "announcement", x: 0, y: 2, w: 1, h: 2, minW: 1, minH: 2 },
    { i: "task", x: 0, y: 4, w: 1, h: 3, minW: 1, minH: 2 },
    { i: "tools", x: 0, y: 7, w: 1, h: 2, minW: 1, minH: 2 },
    { i: "hotNews", x: 0, y: 9, w: 1, h: 4, minW: 1, minH: 3 },
    { i: "placeholder", x: 0, y: 13, w: 1, h: 2, minW: 1, minH: 2 },
  ],
};

interface DashboardGridProps {
  className?: string;
}

const DashboardGrid: React.FC<DashboardGridProps> = ({ className }) => {
  const { message } = App.useApp();

  console.log("DashboardGrid rendering...");
  const [layouts, setLayouts] =
    useState<Record<string, Layout[]>>(DEFAULT_LAYOUTS);
  const [isCustomizing, setIsCustomizing] = useState(false);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [enabledWidgets, setEnabledWidgets] = useState<Record<string, boolean>>(
    {
      announcement: true,
      task: true,
      hotNews: true,
      tools: true,
      billAnalysis: true,
      placeholder: true,
    }
  );
  const [placeholderImages, setPlaceholderImages] = useState<
    Record<string, string>
  >({});

  // 处理布局变化
  const handleLayoutChange = useCallback(
    (_: Layout[], allLayouts: Record<string, Layout[]>) => {
      if (isCustomizing) {
        setLayouts(allLayouts);
        // 保存到localStorage
        localStorage.setItem("dashboard-layouts", JSON.stringify(allLayouts));
      }
    },
    [isCustomizing]
  );

  // 切换自定义模式
  const toggleCustomizing = useCallback(() => {
    setIsCustomizing(!isCustomizing);
    if (!isCustomizing) {
      message.info("进入自定义模式，可以拖拽调整模块位置和大小");
    } else {
      message.success("已保存布局设置");
    }
  }, [isCustomizing, message]);

  // 切换组件显示状态
  const toggleWidget = useCallback((widgetId: string, enabled: boolean) => {
    setEnabledWidgets((prev) => ({
      ...prev,
      [widgetId]: enabled,
    }));
  }, []);

  // 重置布局
  const resetLayout = useCallback(() => {
    setLayouts(DEFAULT_LAYOUTS);
    localStorage.removeItem("dashboard-layouts");
    message.success("已重置为默认布局");
  }, [message]);

  // 处理占位模块图片变化
  const handlePlaceholderImageChange = useCallback(
    (widgetId: string, imageUrl: string) => {
      setPlaceholderImages((prev) => ({
        ...prev,
        [widgetId]: imageUrl,
      }));
    },
    []
  );

  // 渲染组件
  const renderWidget = useCallback(
    (widgetId: string) => {
      const widgetType = WIDGET_TYPES[widgetId as keyof typeof WIDGET_TYPES];
      if (!widgetType) return null;

      const Component = widgetType.component;

      if (widgetId === "placeholder") {
        return (
          <PlaceholderWidget
            backgroundImage={placeholderImages[widgetId]}
            onImageChange={(imageUrl) =>
              handlePlaceholderImageChange(widgetId, imageUrl)
            }
          />
        );
      }

      return <Component />;
    },
    [placeholderImages, handlePlaceholderImageChange]
  );

  // 获取当前启用的布局
  const getCurrentLayouts = useCallback(() => {
    const result: Record<string, Layout[]> = {};
    Object.keys(layouts).forEach((breakpoint) => {
      result[breakpoint] = layouts[breakpoint as keyof typeof layouts].filter(
        (item) => enabledWidgets[item.i]
      );
    });
    return result;
  }, [layouts, enabledWidgets]);

  return (
    <div
      className={`dashboard-grid ${isCustomizing ? "customizing" : ""} ${
        className || ""
      }`}
    >
      {/* 紧凑的天气栏 - 顶部独居一行 */}
      <div className="mb-6 p-3">
        <div className="flex items-center justify-between">
          {/* 左侧：紧凑天气信息 */}
          <div className="flex items-center space-x-4">
            <div className="flex items-center space-x-3">
              <i className="i-mdi-weather-sunny text-2xl text-yellow-500" />
              <div>
                <div className="text-lg font-bold">22°C</div>
                <div className="text-xs text-gray-500">北京 · 晴天</div>
              </div>
            </div>
            <div className="text-xs text-gray-400 hidden sm:block">
              湿度 45% · 风速 3km/h
            </div>
          </div>

          {/* 右侧：图标按钮 */}
          <div className="flex items-center space-x-2">
            <Button
              type={isCustomizing ? "primary" : "default"}
              onClick={toggleCustomizing}
              size="large"
              shape="circle"
              className={`shadow-md transition-all duration-300 ${
                isCustomizing
                  ? "bg-gradient-to-r from-blue-500 to-purple-600 border-0 shadow-lg"
                  : "hover:shadow-lg hover:-translate-y-0.5"
              }`}
              icon={<SettingOutlined />}
              title={isCustomizing ? "完成自定义" : "自定义布局"}
            />

            <Button
              onClick={() => setDrawerVisible(true)}
              size="large"
              shape="circle"
              className="shadow-md hover:shadow-lg hover:-translate-y-0.5 transition-all duration-300"
              icon={<AppstoreOutlined />}
              title="管理模块"
            />

            {isCustomizing && (
              <Button
                onClick={resetLayout}
                size="large"
                shape="circle"
                className="shadow-md hover:shadow-lg hover:-translate-y-0.5 transition-all duration-300"
                icon={<ReloadOutlined />}
                title="重置布局"
              />
            )}
          </div>
        </div>

        {/* 自定义模式提示 */}
        {isCustomizing && (
          <div className="mt-2 text-center">
            <div className="inline-block px-3 py-1 bg-gradient-to-r from-amber-100 to-orange-100 text-amber-700 text-xs rounded-full font-medium animate-pulse">
              ✨ 拖拽调整位置和大小
            </div>
          </div>
        )}
      </div>

      {/* 自定义网格布局 */}
      <ResponsiveGridLayout
        className="layout"
        layouts={getCurrentLayouts()}
        onLayoutChange={handleLayoutChange}
        breakpoints={{ lg: 1200, md: 996, sm: 768, xs: 480, xxs: 0 }}
        cols={{ lg: 12, md: 8, sm: 4, xs: 2, xxs: 1 }}
        rowHeight={70}
        isDraggable={isCustomizing}
        isResizable={isCustomizing}
        margin={[20, 20]}
        containerPadding={[0, 0]}
      >
        {Object.keys(enabledWidgets).map((widgetId) =>
          enabledWidgets[widgetId] ? (
            <div
              key={widgetId}
              className="widget-container"
              data-widget={widgetId}
            >
              {renderWidget(widgetId)}
            </div>
          ) : null
        )}
      </ResponsiveGridLayout>

      {/* 模块管理抽屉 */}
      <Drawer
        title="管理模块"
        placement="right"
        onClose={() => setDrawerVisible(false)}
        open={drawerVisible}
        width={320}
      >
        <List
          dataSource={Object.entries(WIDGET_TYPES)}
          renderItem={([widgetId, widgetType]) => (
            <List.Item>
              <div className="flex items-center justify-between w-full">
                <span>{widgetType.name}</span>
                <Switch
                  checked={enabledWidgets[widgetId]}
                  onChange={(checked) => toggleWidget(widgetId, checked)}
                />
              </div>
            </List.Item>
          )}
        />
      </Drawer>
    </div>
  );
};

export default DashboardGrid;
